package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysArea;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysAreaService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

//import com.ruoyi.develop.utils.ExcelExport;

/**
 * 部门信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/sysArea/area")
public class SysAreaController extends BaseController {
    @Autowired
    private ISysAreaService areaService;

    /**
     * 获取部门列表
     */
//    @PreAuthorize("@ss.hasPermi('sysArea:area:list')")
    @GetMapping("/list")
    public AjaxResult list(SysArea dept) {
//        areaService.insertAreaFromCountryAllCode(3);
//        areaService.insertAreaFromCountryAllCode(4);
//        areaService.insertAreaFromCountryAllCode(5);
        List<SysArea> depts = areaService.selectAreaList(dept);
        return AjaxResult.success(depts);
    }

    @GetMapping("/listByLazyTree")
    public AjaxResult listByLazyTree(SysArea dept) {
        List<SysArea> depts = areaService.selectAreaListLazy(dept);
        for (SysArea area : depts) {
//            SysArea where = new SysArea();
//            where.setParentId(area.getDeptId());
//            List<SysArea> sysAreas = areaService.selectAreaList(where);
//            if(sysAreas.size()>0) {
            area.setHasChildren(true);
//            }
        }
        return AjaxResult.success(depts);
    }


    @GetMapping("/listByLazyTreePart")
    public TableDataInfo listByLazyTreePart(SysArea dept) {
        startPage();
        List<SysArea> depts = areaService.selectAreaListLazy(dept);
        for (SysArea area : depts) {
            area.setHasChildren(true);
        }
        return getDataTable(depts);
    }
    @Log(title = "中高风险地区导入模板下载", businessType = BusinessType.EXPORT)
    @GetMapping("/importTemplate")
    public void importTemplate(SysArea dept, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        response.setContentType("application/force-download");// 设置强制下载不打开
        try {
//            params.put("nowdate", DateUtils.formatDate(new Date(), "yyyy年MM月dd日 HH时mm分"));
//            ExcelExport.exportByTemplate("中高风险地区导入.xlsx", response.getOutputStream(), params);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 查询部门列表（排除节点）
     */
//    @PreAuthorize("@ss.hasPermi('sysArea:area:list')")
    @GetMapping("/list/exclude/{deptId}")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) String deptId) {
        List<SysArea> depts = areaService.selectAreaList(new SysArea());
        Iterator<SysArea> it = depts.iterator();
        while (it.hasNext()) {
            SysArea d = (SysArea) it.next();
            if (deptId.equals(d.getDeptId())
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
//    @PreAuthorize("@ss.hasPermi('sysArea:area:query')")
    @GetMapping(value = "/{deptId}")
    public AjaxResult getInfo(@PathVariable String deptId) {
        return AjaxResult.success(areaService.selectAreaById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysArea dept) {
        List<SysArea> depts = areaService.selectAreaList(dept);
        return AjaxResult.success(areaService.buildAreaTreeSelect(depts));
    }


    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselectArea")
    public AjaxResult treeselectArea(SysArea dept) {
        List<SysArea> depts = areaService.selectAreaTreeList(dept);
        return AjaxResult.success(areaService.buildAreaTreeSelect(depts));
    }

    @GetMapping("/listAreaByLazyTree")
    public AjaxResult listAreaByLazyTree(SysArea dept) {
        List<SysArea> depts = areaService.selectAreaTreeList(dept);
        return AjaxResult.success(areaService.buildAreaTreeSelect(depts));
    }

    @GetMapping("/listAreabyParetnt")
    public TableDataInfo listAreabyParetnt(SysArea dept) {
        startPage();
        List<SysArea> depts = areaService.listAreabyParetnt(dept);
        return getDataTable(depts);
       // return AjaxResult.success(depts);
    }

    /**
     * 根据id 获取上下级
     */
    @GetMapping("/getJson")
    public AjaxResult getJson(SysArea dept) {
        List<Map<String, Object>> depts = areaService.selectdatajson(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 根据id 获取上下级
     */
    @GetMapping("/getAreaLabels")
    public AjaxResult getAreaLabels(SysArea dept) {
        List<Map<String, Object>> depts = areaService.selectdatajsonAll(dept);
        return AjaxResult.success(depts);
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleAreaTreeselect/{roleId}")
    public AjaxResult roleAreaTreeselect(@PathVariable("roleId") String roleId) {
        List<SysArea> depts = areaService.selectAreaList(new SysArea());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", areaService.selectAreaListByRoleId(roleId));
        ajax.put("depts", areaService.buildAreaTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('sysArea:area:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysArea dept) {
        if (UserConstants.NOT_UNIQUE.equals(areaService.checkAreaNameUnique(dept))) {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        return toAjax(areaService.insertArea(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('sysArea:area:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysArea dept) {
        if (UserConstants.NOT_UNIQUE.equals(areaService.checkAreaNameUnique(dept))) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && areaService.selectNormalChildrenAreaById(dept.getDeptId()) > 0) {
            return AjaxResult.error("该部门包含未停用的子部门！");
        }

        if (StringUtils.isNotBlank(dept.getIsDditSon()) && "1".equals(dept.getIsDditSon())) {
            return toAjax(areaService.updateAreaSon(dept));
        }

        dept.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(areaService.updateArea(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('sysArea:area:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public AjaxResult remove(@PathVariable String deptId) {
        if (areaService.hasChildByAreaId(deptId)) {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (areaService.checkAreaExistUser(deptId)) {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(areaService.deleteAreaById(deptId));
    }

    @PostMapping("/changeRiskflag")
    public AjaxResult changeStatus(@RequestBody SysArea dept) {
        return toAjax(areaService.updateArea(dept));
    }

    @PostMapping("/importData")
    public AjaxResult importData(SysArea dept, MultipartFile file) {
        // areaService.importInfo(dept, file);
        // return AjaxResult.success("导入完成");
        Map<String, Object> error = new HashMap<>();
        error = areaService.importInfo(dept, file);
        error.put("code", 200);
        return AjaxResult.success(error);
    }

    @GetMapping("/updateReturnInfoRiskByArea")
    public AjaxResult updateReturnInfoRiskByArea() {
        areaService.updateReturnInfoRiskByArea();
        return AjaxResult.success("生成成功!");
    }

    @GetMapping("/updateSysAreaByJnfyRiskArea")
    public AjaxResult updateSysAreaByJnfyRiskArea() {

        return areaService.updateSysAreaByJnfyRiskArea();
    }


}
